<template>
    <div style="height: 100%;">
        <t-layout style="height: 100%;">
            <t-header style="position: fixed;top: 0;width: 100%;">
                <div style="height: 100%;display: flex;align-items: center;padding: 0 10px;">
                    <t-space>
                        <t-button theme="primary">保存</t-button>
                        <t-button theme="primary" @click="chartVisible = true">插入图表</t-button>
                    </t-space>
                </div>
            </t-header>
            <t-content style="margin-top: 56px;">
                <grid-layout v-model:layout="layout" :col-num="colNum" :row-height="30">
                    <template #default="{ gridItemProps }">
                        <grid-item v-for="item in layout" :key="item.i" v-bind="gridItemProps" :x="item.x" :y="item.y"
                            :w="item.w" :h="item.h" :i="item.i">
                            <component :option="item.option" :is="getComponent(item.viewType)"></component>
                        </grid-item>
                    </template>
                </grid-layout>
            </t-content>
        </t-layout>

        <t-dialog v-model:visible="chartVisible" width="80%" placement="center">
            <template #header>创建图表</template>
            <div style="height: 65vh;padding: 0 20px;">
                <div style="height: 54px;">
                    <t-steps :default-current="chartStepCurrent" :readonly="true">
                        <t-step-item title="步骤1" content="导入数据" />
                        <t-step-item title="步骤2" content="配置图表" />
                    </t-steps>
                </div>
                <div style="margin-top: 10px;height: calc(100% - 64px);" v-if="chartStepCurrent === 1">
                    <div style="height: 32px;">
                        <t-upload :autoUpload="false" action="" @change="chartFileChange" :max="1">
                            <template #fileListDisplay></template>
                        </t-upload>
                    </div>
                    <div style="display: flex;height: calc(100% - 32px);margin-top: 10px;">
                        <div style="height: calc(100% - 20px);flex: 3;">
                            <div id="s2container" style="height: 100%;">
                                <div id="s2table"></div>
                            </div>
                        </div>
                        <div style="height: calc(100% - 20px);flex: 1;padding: 0 10px;">
                            <div v-if="chartColumns.length" style="height: 100%;position: relative;">
                                <div style="font-weight: 600;font-size: 16px;">数据项</div>
                                <div style="margin-top: 10px;">
                                    <t-checkbox-group v-model="checkedColumns">
                                        <t-checkbox v-for="item in chartColumns" :key="item + 'checked'" :label="item"
                                            :value="item" />
                                    </t-checkbox-group>
                                </div>
                                <div style="font-weight: 600;font-size: 16px;margin-top: 30px;">x轴</div>
                                <div style="margin-top: 10px;">
                                    <t-select v-model="chartxAxis">
                                        <t-option v-for="item in chartColumns" :key="item" :label="item"
                                            :value="item"></t-option>
                                    </t-select>
                                </div>
                                <div style="position: absolute;bottom: 0;text-align: right;width: 100%;">
                                    <t-button theme="success" @click="configChart">下一步</t-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div style="margin-top: 10px;height: calc(100% - 64px);display: flex;" v-if="chartStepCurrent === 2">
                    <div style="flex: 1;height: 100%;">
                        <div style="height: 92%;overflow: auto;">
                            <div style="display: flex;align-items: center;">
                                <div style="flex: 1;">图表类型</div>
                                <div style="flex: 3;">
                                    <t-select v-model="chartType">
                                        <t-option label="折线图" value="line" />
                                        <t-option label="柱形图" value="bar" />
                                        <!-- <t-option label="饼状图" value="pie" /> -->
                                    </t-select>
                                </div>
                            </div>
                            <t-collapse borderless>
                                <t-collapse-panel value="0" header="标题">
                                    <template #headerRightContent>
                                        <t-switch v-model="chartOption.title.show" />
                                    </template>
                                    <div v-if="chartOption.title.show">
                                        <div class="form-item">
                                            <div style="flex: 1;">文本</div>
                                            <div style="flex: 3;">
                                                <t-input v-model="chartOption.title.text"></t-input>
                                            </div>
                                        </div>
                                        <div class="form-item">
                                            <div style="flex: 1;">字体颜色</div>
                                            <div style="flex: 3;">
                                                <t-color-picker v-model="chartOption.title.textStyle.color"
                                                    :show-primary-color-preview="false" />
                                            </div>
                                        </div>
                                        <div class="form-item">
                                            <div style="flex: 1;">字号</div>
                                            <div style="flex: 3;">
                                                <t-input-number v-model="chartOption.title.textStyle.fontSize" />
                                            </div>
                                        </div>
                                    </div>
                                </t-collapse-panel>
                                <t-collapse-panel value="1" header="图例">
                                    <template #headerRightContent>
                                        <t-switch v-model="chartOption.legend.show" />
                                    </template>
                                    <div v-if="chartOption.legend.show">
                                        <div class="form-item">
                                            <div style="flex: 1;">图例位置</div>
                                            <div style="flex: 3;">
                                                <t-radio-group v-model="chartOption.legend.bottom">
                                                    <t-radio-button value="auto">上方</t-radio-button>
                                                    <t-radio-button value="0">下方</t-radio-button>
                                                </t-radio-group>
                                            </div>
                                        </div>
                                        <div class="form-item">
                                            <div style="flex: 1;">图例图标</div>
                                            <div style="flex: 3;">
                                                <t-select v-model="chartOption.legend.icon">
                                                    <t-option label="circle" value="circle"></t-option>
                                                    <t-option label="rect" value="rect"></t-option>
                                                    <t-option label="roundRect" value="roundRect"></t-option>
                                                    <t-option label="triangle" value="triangle"></t-option>
                                                    <t-option label="diamond" value="diamond"></t-option>
                                                    <t-option label="pin" value="pin"></t-option>
                                                    <t-option label="none" value="none"></t-option>
                                                </t-select>
                                            </div>
                                        </div>
                                        <div class="form-item">
                                            <div style="flex: 1;">文字颜色</div>
                                            <div style="flex: 3;">
                                                <t-color-picker v-model="chartOption.legend.textStyle.color"
                                                    :show-primary-color-preview="false" />
                                            </div>
                                        </div>
                                        <div class="form-item">
                                            <div style="flex: 1;">字号</div>
                                            <div style="flex: 3;">
                                                <t-input-number v-model="chartOption.legend.textStyle.fontSize" />
                                            </div>
                                        </div>
                                    </div>
                                </t-collapse-panel>
                                <t-collapse-panel value="2" header="数据列">
                                    <div v-if="chartOption.series.length">
                                        <div v-for="item in chartOption.series">
                                            <div>
                                                <div class="form-item">
                                                    <div style="flex: 1;">系列名称</div>
                                                    <div style="flex: 3;">
                                                        <t-input v-model="item.name"></t-input>
                                                    </div>
                                                </div>
                                                <div class="form-item">
                                                    <div style="flex: 1;">图形颜色</div>
                                                    <div style="flex: 3;">
                                                        <t-color-picker v-model="item.itemStyle.color"
                                                            :show-primary-color-preview="false" />
                                                    </div>
                                                </div>
                                                <div class="form-item">
                                                    <div style="flex: 1;">文本标签</div>
                                                    <div style="flex: 3;">
                                                        <t-switch v-model="item.label.show"></t-switch>
                                                    </div>
                                                </div>
                                                <div v-if="item.label.show">
                                                    <div class="form-item">
                                                        <div style="flex: 1;">标签位置</div>
                                                        <div style="flex: 3;">
                                                            <t-select v-model="item.label.position">
                                                                <t-option label="top" value="top"></t-option>
                                                                <t-option label="inside" value="inside"></t-option>
                                                            </t-select>
                                                        </div>
                                                    </div>
                                                    <div class="form-item">
                                                        <div style="flex: 1;">标签颜色</div>
                                                        <div style="flex: 3;">
                                                            <t-color-picker v-model="item.label.color"
                                                                :show-primary-color-preview="false" />
                                                        </div>
                                                    </div>
                                                    <div class="form-item">
                                                        <div style="flex: 1;">标签字号</div>
                                                        <div style="flex: 3;">
                                                            <t-input-number v-model="item.label.fontSize" />
                                                        </div>
                                                    </div>
                                                </div>
                                                <t-divider></t-divider>
                                            </div>
                                        </div>
                                    </div>
                                </t-collapse-panel>
                            </t-collapse>
                        </div>
                        <div style="height: 8%;display: flex;align-items: flex-end;">
                            <t-space>
                                <t-button theme="primary" @click="previewChart">预览</t-button>
                                <t-button theme="success" @click="insertLayout" :disabled="!previewed">插入</t-button>
                            </t-space>
                        </div>
                    </div>
                    <div style="flex: 3;height: 100%;display: flex;align-items: center;justify-content: center;">
                        <div id="chartPreivew"
                            style="height: 100%;width: 98%;border: 1px solid #e8e8e8;border-radius: 4px;">
                        </div>
                    </div>
                </div>
            </div>
            <template #footer></template>
        </t-dialog>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import * as XLSX from 'xlsx'
import * as echarts from 'echarts'
import { TableSheet } from '@antv/s2'
import { MessagePlugin } from 'tdesign-vue-next';
import Echarts from '@/components/Echarts.vue';

//#region echarts
const sheetData = ref([])
const chartVisible = ref(false)
const chartStepCurrent = ref(1)
const chartColumns = ref([])
const checkedColumns = ref([])
const chartType = ref('line')
const chartxAxis = ref('')
const previewed = ref(false)
let chartOption = reactive({
    title: {
        show: false,
        text: '',
        textStyle: {
            color: '#333',
            fontSize: 18
        }
    },
    legend: {
        show: false,
        bottom: 'auto',
        icon: 'circle',
        textStyle: {
            color: '#333',
            fontSize: 12
        }
    },
    tooltip: {},
    xAxis: {},
    yAxis: {
        type: 'value',
    },
    series: []
})

const resetChartVariables = () => {
    chartVisible.value = false
    previewed.value = false
    sheetData.value = []
    chartStepCurrent.value = 1
    chartColumns.value = []
    checkedColumns.value = []
    chartType.value = 'line'
    chartxAxis.value = ''
    chartOption = {
        title: {
            show: false,
            text: '',
            textStyle: {
                color: '#333',
                fontSize: 18
            }
        },
        legend: {
            show: false,
            bottom: 'auto',
            icon: 'circle',
            textStyle: {
                color: '#333',
                fontSize: 12
            }
        },
        tooltip: {},
        xAxis: {},
        yAxis: {
            type: 'value',
        },
        series: []
    }
}

const previewChart = () => {
    chartOption.series.map(item => {
        item.type = chartType.value
    })
    const chart = echarts.init(document.getElementById('chartPreivew'), null, {
        renderer: 'svg',
        devicePixelRatio: 2.5
    });
    chart.setOption(chartOption);
    previewed.value = true
}

const configChart = () => {
    if (!checkedColumns.value.length) {
        MessagePlugin.warning({ content: '至少选择一个数据项' })
        return
    }
    if (chartxAxis.value === '') {
        MessagePlugin.warning({ content: '请选择x轴' })
        return
    }
    chartStepCurrent.value = 2
    let series = []
    let xAxis = []
    for (let i = 0; i < checkedColumns.value.length; i++) {
        let name = checkedColumns.value[i]
        let data = []
        for (let n = 0; n < sheetData.value.length; n++) {
            let item = sheetData.value[n]
            data.push(item[name])
        }
        series.push({
            name: name,
            type: '',
            data: data,
            itemStyle: {
                color: '#5470c6'
            },
            label: {
                show: false,
                position: 'top',
                color: '#333',
                fontSize: 12
            }
        })
    }
    sheetData.value.map(item => {
        xAxis.push(item[chartxAxis.value])
    })
    chartOption.xAxis = {
        type: 'category',
        data: xAxis
    }
    chartOption.series = series
}

const chartFileChange = (files, context) => {
    const file = files[0].raw
    const fileReader = new FileReader()

    fileReader.onload = event => {
        const data = new Uint8Array(event.target.result)
        const { SheetNames, Sheets } = XLSX.read(data, { type: 'array' })
        const workSheets = Sheets[SheetNames[0]]
        const sheetRows = XLSX.utils.sheet_to_json(workSheets);
        sheetData.value = sheetRows
        renderS2(sheetRows)
    }

    fileReader.readAsArrayBuffer(file)
}

const renderS2 = (data) => {
    if (data.length < 2) return
    const columns = Object.keys(data[0])
    chartColumns.value = columns
    const s2DataConfig = {
        fields: { columns: columns },
        data: data
    }
    const s2Options = {
        height: document.getElementById('s2container').offsetHeight,
        width: document.getElementById('s2container').offsetWidth
    }
    const s2 = new TableSheet(document.getElementById('s2table'), s2DataConfig, s2Options)
    s2.render()
}
//#endregion

//#region grid-layout
const layout = ref([])
const index = ref(0)
const colNum = 12

const insertLayout = () => {
    layout.value.push({
        x: (layout.value.length * 4) % (colNum || 12),
        y: layout.value.length + (colNum || 12), // puts it at the bottom
        i: index.value,
        w: 4,
        h: 8,
        viewType: 'echarts',
        option: chartOption
    })
    index.value++
    resetChartVariables()
}

const getComponent = (viewType) => {
    switch (viewType) {
        case 'echarts':
            return Echarts
            break
    }
}
//#endregion

</script>

<style scoped lang="less">
/deep/ .t-form__item {
    margin-bottom: 10px;
}

/deep/ .t-collapse-panel__wrapper .t-collapse-panel__header {
    padding: 10px 0;
}

/deep/ .vue-grid-item {
    background: #fff;
}

.form-item {
    display: flex;
    align-items: center;
    margin: 10px 0;
}
</style>